<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item>
        <el-input v-model="queryParams.number" placeholder="请输入工号" />
      </el-form-item>

      <el-form-item>
        <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item>
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入电话" />
      </el-form-item>

      <el-form-item>
        <el-input v-model="queryParams.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="checkPermission(['edu-admin', 'admin', 'dean-admin'])"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openAddDialog"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini">批量删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <el-dialog title="新增用户" :visible.sync="dialogVisible_add" width="45%" append-to-body>
      <el-form ref="form" :model="teacher" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工号" prop="number">
              <el-input v-model="teacher.number" placeholder="请输入工号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="teacher.name" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="name">
              <el-cascader
                v-model="selectedMajor"
                placeholder="请选择专业"
                :props="{label: 'label', value: 'id', children: 'children'}"
                :options="deptOptions"
                filterable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="margin-left: 25%;">
          <el-button type="primary" @click="add('teacher')">提交</el-button>
          <el-button @click="dialogVisible_add = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加数据对话框表单 -->
    <el-dialog title="编辑信息" :visible.sync="dialogVisible" width="45%" append-to-body>
      <el-form ref="form" :model="teacher" :rules="rules" label-width="100px">
        <el-row>
          <!-- 左侧字段 (占一半空间) -->
          <el-col :span="12">
            <el-form-item label="工号" prop="number">
              <el-input v-model="teacher.number" placeholder="请输入工号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="teacher.name" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>

          <!-- 右侧字段 (占一半空间) -->
          <el-col :span="12">
            <el-form-item label="院校" prop="degree">
              <el-input v-model="teacher.degree" placeholder="请输入院校" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input v-model="teacher.major" placeholder="请输入所学专业" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="户籍地" prop="address">
              <el-input v-model="teacher.address" placeholder="请输入户籍地" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历" prop="almaMater">
              <el-input v-model="teacher.almaMater" placeholder="请输入学历" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="民族" prop="nationality">
              <el-input v-model="teacher.nationality" placeholder="请输入民族" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业时间" prop="graduationDate">
              <el-date-picker v-model="teacher.graduationDate" type="date" placeholder="请选择毕业时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="通讯地址" prop="mailAddress">
              <el-input v-model="teacher.mailAddress" placeholder="请输入通讯地址" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任教学科" prop="teachingSubjects">
              <el-input v-model="teacher.teachingSubjects" placeholder="请输入任教学科名称" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="teacher.birthday" type="date" placeholder="请选择出生日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="entryTime">
              <el-date-picker v-model="teacher.entryTime" type="date" placeholder="请选择入职时间" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="teacher.sex">
                <el-radio :label="0">女</el-radio>
                <el-radio :label="1">男</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份认证" prop="isAuthentication">
              <el-radio-group v-model="teacher.isAuthentication">
                <el-radio :label="0">未认证</el-radio>
                <el-radio :label="1">已认证</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="teacher.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="teacher.phoneNumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-input v-model="teacher.politicalStatus" placeholder="请输入政治面貌" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="post">
              <el-input v-model="teacher.post" placeholder="请输入职位" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="teacher.qq" placeholder="请输入QQ号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号" prop="wxNumber">
              <el-input v-model="teacher.wxNumber" placeholder="请输入微信号" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="个人简介" prop="profile">
              <el-input v-model="teacher.profile" type="textarea" placeholder="请输入个人简介" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="teacher.remarks" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学位证附件" prop="degreeCertificateUrl">
              <el-upload
                class="upload-demo"
                :action="testUrl"
                :on-change="uploadChange"
                :on-success="handleFileSuccess"
                :headers="upload.headers"
                :file-list="fileList"
                :limit="3"
                multiple
              >
                <el-button
                  v-model="teacher.degreeCertificateUrl"
                  size="small"
                  type="primary"
                  @click="updateName = 'degreeCertificateUrl'"
                >上传学位证附件</el-button>
              </el-upload>
            </el-form-item>
          </el-col>

          <!-- 添加毕业证附件上传 -->
          <el-col :span="12">
            <el-form-item label="毕业证附件" prop="diplomaUrl">
              <el-upload
                class="upload-demo"
                :action="testUrl"
                :on-change="uploadChange"
                :on-success="handleFileSuccess"
                :headers="upload.headers"
                :file-list="fileList"
                :limit="3"
                multiple
              >
                <el-button
                  v-model="teacher.diplomaUrl"
                  size="small"
                  type="primary"
                  @click="updateName = 'diplomaUrl'"
                >上传毕业证附件</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交和取消按钮 -->
        <el-form-item v-if="checkPermission(['user'])" style="margin-left: 25%;">
          <el-button type="primary" @click="add_renew('teacher')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 弹框选择角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible_change" width="30%" center>
      <el-form style="margin-left: 18%">
        <el-form-item label="选择角色">
          <el-select v-model="selectedRole" placeholder="请选择角色">
            <el-option label="系主任" value="dean-admin" />
            <el-option label="教务" value="edu-admin" />
            <el-option label="教师" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="margin-top: -2%;">
        <el-button @click="dialogVisible_change = false">取消</el-button>
        <el-button type="primary" @click="assignRole()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" style="width: 50px" />
      <el-table-column prop="number" label="工号" align="center" />
      <el-table-column prop="name" label="姓名" align="center" />
      <el-table-column prop="phoneNumber" label="联系电话" align="center" />
      <el-table-column prop="email" label="邮箱" align="center" />
      <el-table-column prop="sex" label="性别" align="center">
        <template slot-scope="scope">
          <span>
            {{
              scope.row.sex == "0" ? "男" : scope.row.sex == "1" ? "女" : "未知"
            }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="户籍地" align="center" />
      <el-table-column prop="degree" label="学历" align="center" />
      <el-table-column prop="post" label="职位" align="center" />
      <el-table-column prop="profile" label="个人简介" align="center">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top" @mouseenter.native="fetchDocxPreview(scope.row.id)">
            <div ref="docxContainer" style="width: 600px; height: 500px;"></div>
            <div slot="reference" class="name-wrapper">
              {{ scope.row.profile || '无' }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="operUserName" label="创建用户" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <div class="button-group">
            <el-button size="small" type="text" icon="el-icon-s-tools" @click="workFormIds(scope.row.id)">工作经历</el-button>
            <el-button size="small" type="text" icon="el-icon-sort" @click="selectByIds(scope.row.id)">下载</el-button>
            <el-button
              v-if="checkPermission(['edu-admin', 'dean-admin', 'admin'])"
              size="small"
              type="text"
              icon="el-icon-view"
              @click="check_information(scope.row.id)"
            >查看</el-button>
            <el-button
              v-if="checkPermission(['user'])"
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="update(scope.row.id)"
            >修改</el-button>
            <el-button
              size="small"
              type="text"
              icon="el-icon-s-custom"
              @click="titleFormIds(scope.row.id)"
            >工作职称</el-button>
            <el-button
              v-if="checkPermission(['user'])"
              size="small"
              type="text"
              icon="el-icon-document-checked"
              @click="renew(scope.row.id)"
            >更新</el-button>
            <el-button size="small" type="text" icon="el-icon-delete" @click="deleteById(scope.row.id)">删除</el-button>
            <el-dropdown
              v-if="checkPermission(['edu-admin', 'dean-admin', 'admin'])"
              size="mini"
              @command="(command) => handleCommand(command, scope.row.id)"
            >
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-button><el-dropdown-item
                  command="handleResetPwd"
                  icon="el-icon-key"
                >重置密码</el-dropdown-item></el-button>
                <el-button @click="handleAuthRole(scope.row.id)"><el-dropdown-item
                  icon="el-icon-circle-check"
                >分配角色</el-dropdown-item></el-button>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
// import { renderAsync } from 'docx-preview'
import { getToken } from '@/utils/auth'
import {
  add,
  deleteById,
  page,
  selectById,
  update,
  add_renew,
  renew,
  resetUserPwd,
  userUpdateRoleRequest,
  getRoleList,
  preview
} from '@/api/teacher.js'
import { parseTime } from '@/utils'
import checkPermission from '@/utils/permission'
import { deptTreeSelect } from '@/api/user'
// import axios from 'axios'
export default {
  data() {
    return {
      test_file: '',
      timer: null,
      base64Code: '',
      updateName: '',
      test: {
        headers: {
          token: getToken()
        }
      },
      selectedMajor: [],
      checkPermission,
      postOptions: [],
      userId: '',
      // 角色选项
      // 部门树选项
      deptOptions: undefined,
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      dialogVisible_add: false,
      dialogVisible_change: false, // 控制弹框是否显示
      selectedRole: '', // 用户选择的角色
      roleMapping: {
        系主任: 'dean-admin',
        教务: 'edu-admin',
        教师: 'user'
      },
      avatar:
        'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      queryParams: {
        number: '',
        email: '',
        name: '',
        phoneNumber: '',
        ids: []
      },
      fileList: [],
      teacher: {
        number: '', // 工号
        degree: '', // 学历
        id: '',
        // number: '',
        name: '',
        // phoneNumber: '',
        address: '', // 户籍地
        almaMater: '', // 院校
        avatar: '', // 头像地址
        birthday: '', // 出生日期
        entryTime: '', // 入职时间
        graduationDate: '', // 毕业时间
        // birthday: new Date(this.teacher.birthday), // 出生日期
        // entryTime: new Date(this.teacher.entryTime), // 入职时间
        // graduationDate: new Date(this.teacher.graduationDate), // 毕业时间
        isAuthentication: 0, // 身份认证
        email: '', // 邮箱
        phoneNumber: '', // 手机号码
        politicalStatus: '', // 政治面貌
        post: '', // 职位
        profile: '', // 个人简介
        remarks: '', // 备注
        sex: '', // 性别
        major: '', // 专业
        majorId: '', // 专业ID
        wxNumber: '', // 微信号
        qq: '', // QQ号
        teacherCertificationNumber: '', // 教师资格证
        degreeCertificateUrl: '', // 学位证附件
        diplomaUrl: '', // 毕业证附件
        teacherCertificationUrl: '' // 教师资格证附件
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址B
        url: process.env.VUE_APP_BASE_API + 'user/excel-input'

      },
      rules: {
        number: [
          { required: true, message: '请输入员工编号', trigger: 'change' }
          // { pattern: /^\d{3}$/, message: '员工编号必须为3位数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '电话号码必须为11位数字,且以1开头,第二位是3-9之间的数字',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ]
      },
      selected: [],

      // 级联选择器的选项数据
      options: [
        {
          value: 'college1',
          label: '理工农学院',
          children: [
            {
              value: 'department1',
              label: '计算机系',
              children: [
                { value: 'major1', label: '软件工程' },
                { value: 'major2', label: '计算机科学与技术' }
              ]
            },
            {
              value: 'department2',
              label: '电子系',
              children: [
                { value: 'major3', label: '通信工程' },
                { value: 'major3', label: '电子信息工程' },
                { value: 'major4', label: '人工智能' }
              ]
            }
          ]
        },
        {
          value: 'college2',
          label: '文学院',
          children: [
            {
              value: 'department3',
              label: '',
              children: [
                { value: 'major5', label: '专业五' },
                { value: 'major6', label: '专业六' }
              ]
            }
          ]
        }
      ],
      // 配置级联选择器的属性
      cascaderProps: {
        value: 'value', // 每个节点的值属性
        label: 'label', // 每个节点的标签属性
        children: 'children' // 子节点的属性名称
      },
      currentId: '',
      testUrl: process.env.VUE_APP_BASE_API + 'common/upload', // 下载模板的接口地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/user/diploma', // 上传接口 URL
      uploadUrl1: process.env.VUE_APP_BASE_API + '/user/degreeCertificate',
      multipleSelection: [],
      filename: '',
      tableData: [],
      list: null,
      total: 0,
      fileName: '',
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      }
    }
  },
  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
    this.getDeptTree()
  },
  methods: {
    tests(id) {
      preview(id).then(response => {
        console.log(response.data)
        this.base64Code = response.data
        // 将Base64字符串转换为Blob对象并进行预览
        try {
          const base64String = response.data
          const byteCharacters = atob(base64String.split(',')[1])
          const byteNumbers = new Array(byteCharacters.length)
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i)
          }
          const byteArray = new Uint8Array(byteNumbers)
          const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })

          // 使用docx-preview进行预览
          renderAsync(blob, this.$refs.docxContainer)
        } catch (error) {
          console.error('Error fetching or previewing docx:', error)
        }
      }).catch(error => {
        console.error('Error fetching preview data:', error)
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    titleFormIds(id) {
      this.$router.push({ path: `/schoolmanage/index6/${id}`, params: { id: id }})
    },
    uploadChange(file, fileList) {
      console.log(file, fileList)
    },
    handleExceed() {
      this.$message.error('上传文件超出限制')
    },
    getUserRolesList() {
      getRoleList().then(response => {
        console.log(response.data)
        const roleMap = response.data
        // 将 Map 转换为数组，每个元素是一个对象，包含 label 和 value 属性
        this.postOptions = Array.from(Object.entries(roleMap), ([key, value]) => ({ label: value, value: key }))
        console.log(this.postOptions)
      }).catch(error => {
        console.error('获取角色列表失败:', error)
      })
    },

    handleChange(value) {
      // 当选择发生变化时，打印当前选择的结果
      console.log('当前选择的值：', value)
    },
    workFormIds(id) {
      this.$router.push({ path: `/schoolmanage/data/${id}`, params: { id: id }})
    },
    // 更新
    // 更新
    renew(id) {
      this.dialogVisible = true
      // 获取教师信息
      selectById(id)
        .then(result => {
          if (result.code === 1) {
            this.teacher = result.data
            // 对表单进行验证
            try {
              this.$refs['form'].validate(valid => {
                if (valid) {
                  // 提交更新请求
                  renew(this.teacher.id, this.teacher)
                    .then(response => {
                      if (response.code === '1') {
                        this.dialogVisible = false // 关闭对话框
                        this.page() // 重新加载页面数据
                        this.$message({ message: '信息更新成功', type: 'success' })
                      } else {
                        this.$message.error(response.msg)
                      }
                    })
                    .catch(error => {
                      this.$message.error('更新失败，请稍后再试')
                      console.error('更新请求失败:', error) // 输出详细的错误信息
                    })
                } else {
                  this.$message.error('表单验证失败')
                }
              })
            } catch (error) {
              this.$message.error('表单验证时发生错误')
              console.error('表单验证错误:', error) // 输出详细的错误信息
            }
          } else {
            this.$message.error('获取教师信息失败')
          }
        })
        .catch(error => {
          this.$message.error('请求失败，请稍后再试')
          console.error('请求失败:', error) // 输出详细的错误信息
        })
    },
    add_renew() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 提交更新请求
          add_renew(this.teacher)
            .then(response => {
              console.log('响应:', response)

              if (response.code === 1) { // 如果响应的code表示成功
                this.dialogVisible = false // 关闭对话框
                this.page() // 重新加载页面数据
                this.$message({ message: '信息更新成功', type: 'success' })
              } else {
                // 如果响应中有 msg 字段，显示错误信息
                this.$message.error(response.msg || '更新失败，请稍后再试')
              }
            })
            .catch(error => {
              // 打印错误信息，查看请求失败的原因
              console.error('请求错误:', error)
              this.$message.error('更新失败，请稍后再试')
            })
        }
      })
    },
    // 查询分页数据
    page() {
      const requestData = {
        number: this.queryParams.number,
        email: this.queryParams.email,
        name: this.queryParams.name,
        phoneNumber: this.queryParams.phoneNumber,
        current: this.current,
        pageSize: this.pageSize
      }
      // 发送请求
      page(requestData)
        .then((res) => {
          this.totalCount = res.data.total
          this.tableData = res.data.records
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },

    selectByIds(id) {
      this.$confirm('确定导出选中数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.filename = this.tableData.find((item) => item.id === id).name + '-' + new Date().getTime() + '.docx'
        this.download(process.env.VUE_APP_BASE_API + '/user/information', { userId: id }, this.filename)
      })
    },
    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    openAddDialog() {
      this.dialogVisible_add = true
      this.getUserRolesList()

      // 清空teacher对象中的各个属性值，以清除输入框的值
      this.teacher = {
        id: '',
        number: '',
        name: '',
        degree: '',
        major: '',
        address: '',
        almaMater: '',
        nationality: '',
        graduationDate: '',
        mailAddress: '',
        teachingSubjects: '',
        birthday: '',
        entryTime: '',
        sex: '',
        isAuthentication: '',
        email: '',
        phoneNumber: '',
        politicalStatus: '',
        post: '',
        qq: '',
        wxNumber: '',
        profile: '',
        remarks: '',
        degreeCertificateUrl: '',
        diplomaUrl: '',
        role: 'user' // 设置默认角色为 "user" (教师)
      }

      // 清空与级联选择器等相关联的值（如果有需要）
      this.value = []

      this.$nextTick(() => {
        // 可能需要确保视图更新完成后才做其他操作
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 选中数据时下载选择数据
      if (this.multipleSelection.length > 0) {
        this.queryParams.ids = this.multipleSelection.map((item) => item.id) // 传递筛选后的id数组
        this.filename = '选中教师-' + new Date().getTime() + '.xlsx'
        // eslint-disable-next-line no-empty
      } else {
        this.queryParams.ids = [] // 传递空数组
        if (this.queryParams.name === '' && this.queryParams.number === '' && this.queryParams.phoneNumber === '' && this.queryParams.email === '') {
          this.filename = '全部教师-' + new Date().getTime() + '.xlsx'
          // eslint-disable-next-line no-empty
        } else {
          this.filename = '筛选教师-' + new Date().getTime() + '.xlsx'
        }
      }
      this.filename = '资料-' + new Date().getTime() + '.xlsx'
      this.download(process.env.VUE_APP_BASE_API + '/user/excel-output', this.queryParams, this.filename)
      // this.download(process.env.VUE_APP_BASE_API + '/user/excel-output', this.queryParams, `user_${new Date().getTime()}.xlsx`)
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(process.env.VUE_APP_BASE_API + '/user/template', {
      }, `教师信息模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      console.log('上传成功:', response.data.fileUrl)
      if (this.updateName === 'diplomaUrl') {
        this.teacher.diplomaUrl = response.data.fileUrl
      } else if (this.updateName === 'degreeCertificateUrl') {
        this.teacher.degreeCertificateUrl = response.data.fileUrl
      }
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + (response.msg == null ? '导入成功' : response.msg) + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },

    clear() {
      this.queryParams = { number: '', name: '', phoneNumber: '' }
      this.page()
    },

    // 添加数据
    add() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let operator

          this.teacher.majorId = this.selectedMajor[2]
          if (this.teacher.id) {
            // 修改
            operator = update(this.teacher)
          } else {
            console.log('this.teacher', this.teacher)
            operator = add(this.teacher)
          }

          operator.then((resp) => {
            if (resp.code == '1') {
              this.dialogVisible_add = false
              this.page()
              this.$message({ message: '恭喜你，保存成功', type: 'success' })
              this.dialogVisible = false
            } else {
              this.$message.error(resp.msg)
            }
          })
        }
      })
    },
    check_information(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      this.currentId = id
      this.getUserRolesList()
      // 2. 发送请求
      selectById(id).then((result) => {
        if (result.code == 1) {
          this.teacher = result.data
        } else {
          this.$message.error('获取用户信息失败')
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      this.currentId = id
      this.getUserRolesList()
      // 2. 发送请求
      selectById(id).then((result) => {
        if (result.code == 1) {
          this.teacher = result.data
        } else {
          this.$message.error('获取用户信息失败')
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleResetPwd':
          this.handleResetPwd(row)
          break
        default:
          break
      }
    },
    // 学位证上传
    handleDegreeCertificateSuccess(fileList) {
      this.teacher.degreeCertificateUrl = fileList.map(item => item.response?.fileUrl || item.url) // 保存文件URL
    },
    // 毕业证上传
    handleDiplomaSuccess(fileList) {
      this.teacher.diplomaUrl = fileList.map(item => item.response?.fileUrl || item.url) // 保存文件URL
    },
    // 文件上传前的处理
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf'
      const isLt5M = file.size / 1024 / 1024 < 5 // 限制文件大小为5MB
      if (!isPDF) {
        this.$message.error('只能上传PDF文件')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB')
      }
      return isPDF && isLt5M
    },
    // 删除学位证文件
    handleDegreeCertificateRemove(fileList) {
      this.teacher.degreeCertificateUrl = fileList.map(item => item.response?.fileUrl || item.url)
    },
    // 删除毕业证文件
    handleDiplomaRemove(fileList) {
      this.teacher.diplomaUrl = fileList.map(item => item.response?.fileUrl || item.url)
    },
    /** 重置密码按钮操作 */
    async handleResetPwd(row) {
      try {
        // 等待用户确认
        await this.$confirm(
          `你要将用户【${row.userName}】的密码重置吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        console.log('=====userId', row)
        // 用户确认后调用接口重置密码
        await resetUserPwd({ userId: row.id, newPassword: '123456', isReset: true }) // 第三个参数为 true 表示重置密码
        this.$message.success(`重置成功`)
      } catch (error) {
        // 捕获取消操作或接口调用错误
        if (error === 'cancel') {
          this.$message.info('已取消操作')
        } else {
          this.$message.error('重置失败，请稍后再试')
          console.error(error)
        }
      }
    },
    /** 分配角色操作 */
    handleAuthRole(id) {
      // 打开弹框
      this.currentId = id
      console.log('分配角色', id)
      this.dialogVisible_change = true
      this.selectedRole = '' // 清空选中的角色
    },

    // 确认分配角色
    assignRole() {
      const selectedRole = this.selectedRole
      if (selectedRole) {
        // 获取后端对应的角色值
        const roleName = Object.keys(this.roleMapping).find(key => this.roleMapping[key] === selectedRole)

        if (!roleName) {
          this.$message.error('无效的角色选择')
          return
        }

        const requestData = {
          id: this.currentId,
          roles: [selectedRole]
        }

        // 调用接口更新角色
        userUpdateRoleRequest(requestData)
          .then((res) => {
            if (res.code == 1) {
              this.$message.success(`角色分配成功，用户被设置为${roleName}`)
              this.dialogVisible_change = false // 关闭弹框
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch((error) => {
            this.$message.error('角色分配失败')
            console.error(error)
          })
      } else {
        this.$message.error('请选择有效的角色')
      }
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    // 删除员工信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 2. 发送AJAX请求
          deleteById(id).then((resp) => {
            if (resp.code == 1) {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },

    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
